package newNetty;

import com.alibaba.fastjson.JSON;
import config.MessageBo;
import config.UserInfoBO;
import constant.MessageConstant;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import static config.Constants.mapUser;
import static config.Constants.userIdAddress;

/**
 * @author : GuoFei
 * @date : 2018/11/21 11:02
 */
@Component
@Configuration
public class WebScoketHandler {

    private static final Logger logger = LoggerFactory.getLogger(WebScoketHandler.class);

    /**
     * 处理器
     * @param ctx 信息流
     * @param messageBo 信息体
     */
    public void handler(ChannelHandlerContext ctx, MessageBo messageBo){
        logger.info("信息请求：{},信息体：{}", JSON.toJSONString(ctx),JSON.toJSONString(messageBo));
        if (ctx != null && messageBo != null) {
            UserInfoBO userInfoBO;
            switch (messageBo.getType()) {
                case MessageConstant.ADD_USER:
                    mapUser.put(messageBo.getId(),new UserInfoBO(messageBo.getMessage(),messageBo.getId(),ctx));
                    userIdAddress.put(ctx.channel().remoteAddress().toString(),messageBo.getId());
                    ctx.channel().write(new TextWebSocketFrame("欢迎你："+ctx.channel().remoteAddress()));
                    break;
                case MessageConstant.RECEIVE_MESSAGE:
                    userInfoBO = getUserInfoBo(messageBo.getId());
                    userInfoBO.getCtx().write(new TextWebSocketFrame("你好，收到你的信息了:"+messageBo.getMessage()));
                    break;
                    default:
            }
        }
    }

    private UserInfoBO getUserInfoBo(int id){
        return mapUser.get(id);
    }



}
